﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco.NodeFactory;
using Vega.USiteBuilder;
using SPCFMedicineInformer.DocumentTypes;
using System.Text;
using SPCFMedicineInformer.Constants;
using umbraco.cms.businesslogic.web;
using umbraco.BusinessLogic;
using SPCFMedicineInformer.Helpers;
using umbraco;

namespace SPCFMedicineInformer.Masterpages
{
    public partial class Admin_SymptomDetails : System.Web.UI.MasterPage
    {
        int id;
        protected void Page_Load(object sender, EventArgs e)
        {
            int tempInt;
            id = Request.QueryString["id"] != null ? int.TryParse(Request.QueryString["id"].ToString(), out tempInt) ? tempInt : 1 : 0;
            bool isNew = Request.QueryString["n"] != null ? Request.QueryString["n"].ToString() == "1" ? true : false : false;
            btnDelete.Visible = id > 0 ? true : false;
            if (!IsPostBack)
            {
                BindDropdowns();
                if (id > 0)
                {
                    Node node = new Node(id);
                    var s = node != null && node.NodeTypeAlias == "Symptom" ? ContentHelper.GetByNodeId<Symptom>(id) : null;
                    if (s != null)
                    {
                        hiddenOrig_Category_Id.Value = s.MedicineCategoryId;
                        txtSymptom.Text = s.SymptomName;
                        txtLink.Text = s.SymptomLink;
                        txtDescription.Text = s.SymptomDescription;
                        ddlCategory.SelectedValue = s.MedicineCategoryId;
                        if (isNew)
                            FormHelper.ShowMessage(MessageType.Done, "Symptom Succesfully Saved!",MsgLiteral);
                        ShowContent(true);
                    }
                    else
                    {
                        ShowContent(false);
                        
                    }
                }
            }
        }
        void ShowContent(bool b)
        {
            plcContent.Visible = b;
            plcError.Visible = !b;
        }
        void Update()
        {
            if (id > 0)
            {
                int tempInt;
                int catId = int.Parse(ddlCategory.SelectedValue);
                int orig_cat_id = int.TryParse(hiddenOrig_Category_Id.Value, out tempInt) ? tempInt : 0;
                var d = new Document(id);
                if (d != null)
                {
                    TransferDetailsToUmbraco(d);
                    if (catId != orig_cat_id)
                    {
                        var sympContainer = ContentHelper.GetByNodeId<MedicineCategory>(catId).GetChildren<SymptomListing>().FirstOrDefault();
                        if (sympContainer != null)
                            UmbracoNodeHelper.MoveNode(sympContainer.Id, id);
                    }
                }
            }
            
        }
        int AddSymptom()
        {
            DocumentType docType = DocumentType.GetByAlias("Symptom");
            int categoryId = int.Parse(ddlCategory.SelectedValue) ;
            if (categoryId > 0)
            {
                var sympContainer = ContentHelper.GetByNodeId<MedicineCategory>(categoryId).GetChildren<SymptomListing>().FirstOrDefault();
                if (sympContainer != null)
                {
                    Document newDoc = Document.MakeNew(txtSymptom.Text, docType, User.GetUser(0), sympContainer.Id);
                    TransferDetailsToUmbraco(newDoc);
                    if (newDoc != null)
                        return newDoc.Id;
                }
            }
            return 0;
        }
        void BindDropdowns()
        {
            var categoryList = NodeLocator.GetNodesOfExactType<MedicineCategory>();
            ddlCategory.Items.Clear();
            ddlCategory.DataSource = categoryList;
            ddlCategory.DataTextField = "Name";
            ddlCategory.DataValueField = "Id";
            ddlCategory.DataBind();
            ddlCategory.Items.Insert(0, new ListItem("Choose...", "0"));
        }
        void TransferDetailsToUmbraco(Document d)
        {
            d.Text = txtSymptom.Text;
            d.getProperty(UmbracoPropertyName.SYMPTOM_NAME).Value = txtSymptom.Text;
            d.getProperty(UmbracoPropertyName.SYMPTOM_LINK).Value = txtLink.Text;
            d.getProperty(UmbracoPropertyName.SYMPTOM_CATEGORY_NAME).Value = ddlCategory.Items[ddlCategory.SelectedIndex].Text;
            d.getProperty(UmbracoPropertyName.SYMPTOM_CATEGORY_ID).Value = ddlCategory.SelectedValue;
            d.getProperty(UmbracoPropertyName.SYMPTOM_DESCRIPTION).Value = txtDescription.Text;
            d.Publish(User.GetUser(0));
            umbraco.library.UpdateDocumentCache(d.Id);
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (IsValidate())
            {
                if (id > 0)
                {
                    Update();
                    FormHelper.ShowMessage(MessageType.Done, "Symptom Succesfully Saved!", MsgLiteral);
                }
                else
                {
                    id = AddSymptom();
                    Response.Redirect("/admin/utilities/symptoms-listing/symptom-entry.aspx?id=" + id.ToString() + "&n=1");
                }
            }
            
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("/admin/utilities/symptoms-listing/");
        }
        bool IsValidate()
        {
            bool result = true;
            int tempInt;
            int catId = int.Parse(ddlCategory.SelectedValue);
            int orig_cat_id = int.TryParse(hiddenOrig_Category_Id.Value,out tempInt) ? tempInt : 0;
            var sb = new StringBuilder();
            var msgFormat = "<p class=\"{0}\">{1}</p>";

            if (ddlCategory.SelectedIndex <= 0)
            {
                sb.AppendLine(string.Format(msgFormat, "msg warning", "Category is required!"));
                result = false;
            }
            if (string.IsNullOrWhiteSpace(txtSymptom.Text))
            {
                sb.AppendLine(string.Format(msgFormat, "msg warning", "Symptom Name is required!"));
                result = false;
            }
            else if (orig_cat_id != catId && catId > 0)
            {
                if (ContentHelper.GetByNodeId<MedicineCategory>(catId).GetChildren<SymptomListing>().FirstOrDefault().GetChildren<Symptom>().Where(a=>a.Name.ToLower() == txtSymptom.Text.ToLower()).Count() > 0)
                {
                    result = false;
                    sb.AppendLine(string.Format(msgFormat, "msg error", "Symptom Name exist!"));
                }
            }
            if (!result)
            {
                MsgLiteral.Visible = true;
                MsgLiteral.Text = sb.ToString();
            }
            return result;
        }
        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            Response.Redirect("/admin/utilities/symptoms-listing/symptom-entry.aspx");
        }
        void Delete(int id)
        {
            if (id > 0)
            {
                Document doc = new Document(id);
                if (doc.Published)
                {
                    doc.UnPublish();
                    library.UnPublishSingleNode(doc.Id);
                }
                doc.delete();
                Response.Redirect("/admin/utilities/symptoms-listing/");
            }
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            Delete(id);
        }
    }
}